package org.osami.gateway.watteco;

import java.io.IOException;
import java.util.logging.Logger;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.osami.gateway.sensor.data.IUpdatableSense;
import org.osami.gateway.sensor.data.SenseNode;
import org.osami.gateway.watteco.interfaces.IW1NodeIPv6;
import org.osami.gateway.watteco.interfaces.IWattecoSmartplugIPv6;
import org.osgi.service.device.Constants;

@Component
@Provides
public class WattecoSmartplugIPv6 implements IWattecoSmartplugIPv6
{
    private static final Logger logger = Logger.getLogger(WattecoSmartplugIPv6.class.getName());

    public final static int MATCH_SERIAL = 10;
    public final static int MATCH_TYPE = 5;

    public final static String POWER_KEY = "Power";

    @Requires
    private IW1NodeIPv6 controller;

    @ServiceProperty(name = Constants.DEVICE_CATEGORY,
                     value = "{Watteco}")
    private String[] categories;

    @ServiceProperty(name = Constants.DEVICE_SERIAL,
                     mandatory = true)
    private String serial;

    @ServiceProperty(name = "device.type",
                     value = "wattecospipv6")
    private String type;

    @ServiceProperty(value = SenseNode.TOPIC_PREFIX + "wattecosp")
    private String topic;

    @Requires(id = "power",
              filter = "(&(sense.type=Power)(device.id=<to-be-set-dynamically>))",
              optional = true)
    private IUpdatableSense power;

    public void noDriverFound() {
        logger.info("WattecoSmartplug.noDriverFound()");
    }

    public void switchOn() throws IOException
    {
        controller.switchOn(serial);
    }

    public void switchOff() throws IOException
    {
        controller.switchOff(serial);
    }

    public void toggleSwitch() throws IOException
    {
        controller.toggleSwitch(serial);
    }

    public int getSwitchState() throws IOException
    {
        return controller.getSwitchState(serial);
    }

    public void setSwitchState(boolean state) throws IOException
    {
        controller.setSwitchState(serial, state);
    }

    public void startMeasurements() throws IOException
    {
        controller.startMeasurements(serial);
    }

    public int getMeasurement() throws IOException
    {
        int value = controller.getMeasurement(serial);
        power.update(value);
        return value;
    }

    public String getID()
    {
        return serial;
    }
}
